from pyE17 import io
import matplotlib.pyplot as plt
import ptycho2 as ptycho
import numpy as np
import sys


#h5 = io.h5read(filename)
#img = h5['eh5']['images'][0]
#plt.figure()
#plt.imshow(img)
#plt.show()

def prep_eiger_file(base_path,user,dpsize,ctr,detector_distance,first_scan,last_scan,step_size_y,sx,nx,dat_file):
    # Need to "hack" the defaults for continuous scans
    ptycho.cSAXS.FILENAME_MULTEXP_PATTERN = '{read_path}/{prefix}{scan_number:05d}_{index}_00000.{file_extension}'
    ptycho.cSAXS.FILENAME_PATTERN = '{read_path}/{prefix}{scan_number:05d}_{index}_00000.{file_extension}'

    ptycho.cSAXS.READ_PATH_PATTERN = '{base_path}'
    # Empty parameter structure
    p = ptycho.Param()

    p.verbose_level = 3
    p.interactive = False                         # Not used for now
    p.base_path = base_path
    p.user = user
    #p.scan_number = 300
    p.dpsize = dpsize                          # Crop size (used to be "asize")
    p.ctr = ctr                               # Center of cropped array
    #p.motors = ('py', 'px')                      # Motor names in y and x
    #p.motors_multiplier = 1e-3                    # Multiplier to convert motor values to meters
    p.motors = None                               # Motor names in y and x
    p.energy = 6.2                                # Energy in keV
    p.detector_pixel_size = 75e-6                # Detector pixel size
    p.detector_distance = detector_distance                    # Detector distance
    p.scan_type = None                            # None (use spec), or 'raster', 'round', 'round_roi'

    p.motors_multiplier = 1e-3
    p.spec_filename = ptycho.cSAXS.spec.SpecInfo(base_path + '/'+dat_file)
#     p.spec_filename = ptycho.cSAXS.spec.SpecInfo(base_path + '/specES1/dat-files/'+dat_file)
    p.pilatus_dir = 'eiger'
#     p.pilatus_mask = base_path + '/matlab/ptycho/eiger_valid_mask.mat'
    p.pilatus_mask = base_path + '/eiger_valid_mask.mat'
    p.isEigerFile = False
    p.isEigerRoundScan = True
#    specinfo = ptycho.cSAXS.spec.SpecInfo(base_path + '/specES1/dat-files/'+dat_file)


    p.scan_number = first_scan
    ptycho.cSAXS.prepare_data(p)


user = 'e14438'
dpsize = (230,230)
ctr = 'inter'#(276, 376)#
detector_distance= 7.2122
first_scan = 12686
last_scan = 9452
base_path = '/space/ptychography/S12686'
#base_path = '/home/philipp/Documents/master'
dat_file = 'specES1_started_2013_03_20_1108.dat'
scan = (first_scan,last_scan,250.000,20)

prep_eiger_file(base_path, user, dpsize, ctr, detector_distance, scan[0], scan[1], scan[2]*1e-9,scan[2]*1e-9,scan[3],dat_file)


